package com.gqr.threadobjectclasscommonmethods;

/**
 * Copyright (C), 2020-2024,gqr
 * FileName:WaitNotifyReleaseOwnMonitor
 * author:guqingrong
 * Date:2024-04-22 21:12
 * Description:证明wait只释放当前的那把锁
 * History:
 * <author>    <time>    <version>    <desc>
 * 作者姓名     修改时间     版本号        描述
 */
public class WaitNotifyReleaseOwnMonitor {
    private static volatile Object resourceA = new Object();
    private static volatile Object resourceB = new Object();

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {

            @Override
            public void run() {
                synchronized (resourceA) {
                    System.out.println("ThreadA got resourceA lock.");
                    synchronized (resourceB) {
                        System.out.println("ThreadA got resourceB lock.");
                        try {
                            System.out.println("ThreadA releases resourceA lock.");

                            resourceA.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });


        Thread thread2 = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (resourceA) {
                    System.out.println("ThreadB got resourceA");
                    System.out.println("ThreadB try to get resourceB");

                    synchronized (resourceB) {
                        System.out.println("ThreadB got resourceB");

                    }
                }
            }
        });

        thread1.start();
        thread2.start();
    }
}
